package lyx.game.utils
{
	import flash.utils.getTimer;
	
	import lyx.utils.log.Logger;
	
	/**
	 * KeyState表示此时刻，键盘按键状态。
	 * 通过KeyState可以知道按键的状态，以及在设定的compages_press_interval间隔
	 * 所完成的连续按键组合。
	 */	
	public class KeyState
	{
		private var _last_keycode:int = -1;
		public function get last_keycode():int
		{
			return _last_keycode;
		}
		
		private var _last_is_keydown:Boolean = false;
		public function get last_is_keydown():Boolean
		{
			return _last_is_keydown;
		}
		
		private var _last_is_keyup:Boolean = false;
		public function get last_is_keyup():Boolean
		{
			return _last_is_keyup;
		}
		/** 
		 * 有效的连续按键时间间隔 
		 */		
		public var compages_press_interval:int = 500;
		
		/**
		 * 同时处于按下状态的按键 
		 */		
		public const simultaneity_pressing:Array = [];
		/**
		 * 到此时为止，有效的连续按键组合 
		 */		
		public const compages_pressed:Array = [];
		/**
		 * 上一个按键按下的时间 
		 */		
		private var _last_press_time:int = 0;
		
		/**
		 * 检查按键是否已经处于按下状态
		 * @param keycode 按键的数字代码
		 * @return 如果按键处于按下状态返回true，否则false
		 * 
		 */		
		public function isKeyPressing(keycode:int):Boolean
		{
			var is_pressing:Boolean = simultaneity_pressing.indexOf(keycode)!=-1 ? true:false;
			return is_pressing;
		}
		
		/**
		 * 从所有按下的按键中取出包含在keys数组里面的按键，并组成一个数组返回。
		 * （数组中按键的顺序是根据按键按下的先后次序进行排列。）
		 * @param keys
		 * @return 
		 * 
		 */		
		public function getKeysInArray(keys:Array):Array
		{
			var values:Array = [];
			for each(var keycode:int in simultaneity_pressing)
			{
				var key_index:int = keys.indexOf(keycode);
				if(key_index!=-1)
				{
					values.push(keycode);
				}
			}
			return values;			
		}
		
		/**
		 * 将该按键添加到按下状态数组中 
		 * @param keycode
		 */		
		public function addKeyForKeyDown(keycode:int):void
		{
			if(!isKeyPressing(keycode))
			{
				simultaneity_pressing.push(keycode);
				_last_is_keydown = true;
				_last_is_keyup = false;
				_last_keycode = keycode;
				
				var press_time:int = getTimer();
				if(compages_pressed.length!=0&&(press_time-_last_press_time)>compages_press_interval)
				{
					Logger.getInstance().debug("Last compages press keys is:{0}",compages_pressed.join('-'));
					compages_pressed.splice(0,compages_pressed.length);	
				}
				compages_pressed.push(keycode);
				_last_press_time = press_time;
			}
		}
		
		/**
		 * 将该按键从按下状态数组中删除 
		 * @param keycode
		 * 
		 */		
		public function deleteKeyForKeyUp(keycode:int):void
		{
			var key_index:int = simultaneity_pressing.indexOf(keycode);
			if(key_index!=-1)
			{
				simultaneity_pressing.splice(key_index,1);
				_last_is_keyup = true;
				_last_is_keydown = false;
				_last_keycode = keycode;
			}
		}
	}
}